package com.test.cofig;

import com.netflix.discovery.DiscoveryClient;
import feign.Client;
import feign.Request;
import feign.Response;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient;

import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 *  直接继承 原生态的客户端
 */
public class MyFeignTrafficRedrectClient2 extends FeignBlockingLoadBalancerClient {// OR LoadBalancerFeignClient{
    public MyFeignTrafficRedrectClient2(Client delegate, LoadBalancerClient loadBalancerClient,
                                        LoadBalancerClientFactory loadBalancerClientFactory,DiscoveryClient dis) {
        super(delegate, loadBalancerClient, loadBalancerClientFactory);
        this.dis = dis ;
    }
    private final static Logger log = LoggerFactory.getLogger(MyFeignTrafficRedrectClient2.class);
    private final static  String HTTPS="https://";
    private final static  String HTTP="http://";
    private final    DiscoveryClient dis ;
    private final static String PATH_SP= "/" ;
    private String buiderUrl(URI originalUrl , String hostName){
        return new StringBuilder(hostName).append(originalUrl.getPath().startsWith(PATH_SP)?originalUrl.getPath():
                PATH_SP+originalUrl.getPath()).append(originalUrl.getQuery()==null?"?"+originalUrl.getQuery():"")
                .toString();
    }



    @Override
    public Response execute(Request request, Request.Options options) throws IOException {
        if(!TrafficRedrectUtil.isOpen()){
            return super.execute(request,options);
        }
        URI originalUrl = URI.create(request.url());
        String clientName = originalUrl.getHost().toUpperCase() ;
        String dstName = clientName ;
        Request newReq = request ;
        String newUrl = request.url().toLowerCase().startsWith(HTTP)?HTTP:HTTPS;
        Map<String, Collection<String>> head = new LinkedHashMap<>() ;
        head.putAll(request.headers());
        TrafficRedrectUtil.addRouteTab(head);
        boolean isLocalServer =false ;
        if(StringUtils.isNotBlank(TrafficRedrectUtil.getKey(clientName))){
            dstName = TrafficRedrectUtil.getKey(clientName) ;
            if(Objects.nonNull(dis.getApplication(dstName))){// 有应用  http://dstName/url
                newUrl += buiderUrl(originalUrl ,dstName );
                isLocalServer = true ;
            }else{// http://clientName/url
                newUrl+=buiderUrl(originalUrl,clientName);
            }
        }else {// 当前clientName 不需要流量转发
            newUrl+=buiderUrl(originalUrl,clientName);// http://clientName/url
        }

        newReq = Request.create(request.method(),newUrl,head, request.body(), request.charset());
        if(isLocalServer){
            log.info("---Feign进行流量转发到新服务---原始服务名字:{}---新服务名字:{}--转发以后URL:{}",
                    clientName,dstName,newUrl);
        }
        return super.execute(newReq ,options);
    }


}
